﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using VIBlend.WPF.Controls;
using System.Globalization;

namespace AnonsaiWPF.CSharp.DataGridViewDemos
{
    
    [Category("VIBlend.WPF.Examples")]
    public partial class TextFormatting : Window, IWindow
    {
        DataTemplate columnProductDataTemplate;
        DataTemplate unitPriceColumnDataTemplate;
        CultureInfo[] info = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
        DataTemplate cellNumberTemplate;

        #region IWindow Members

        public void DetachContent()
        {
            RemoveLogicalChild(Content);
        }

        public Grid Root
        {
            get
            {
                return this.LayoutRoot;
            }
        }
        #endregion

        public TextFormatting()
        {
            InitializeComponent();

            DecimalValue = 2;
            DateTimeFormatString = "d";
            CurrentCulture = null;
            
            for (int i = 0; i < info.Length; i++)
            {
                this.CultureSettings.Items.Add(info[i].DisplayName);
            }

            this.CultureSettings.Text = "";

            PrepareGridData();

            this.cellNumberTemplate = this.Resources["cellNumberTemplate"] as DataTemplate;
            this.columnProductDataTemplate = this.Resources["columnProductDataTemplate"] as DataTemplate;
            this.unitPriceColumnDataTemplate = this.Resources["unitPriceColumnDataTemplate"] as DataTemplate;
           
            dataGrid.ColumnsHierarchy.AllowResize = false;
            dataGrid.RowsHierarchy.AllowResize = false;

            dataGrid.ItemsSource = listSaleRecord;
            UpdateColumnsWidth();
            
            dataGrid.RowsHierarchy.Visible = false;
          
            dataGrid.ColumnsHierarchy.AllowDragDrop = false;
            dataGrid.ColumnsHierarchy.AllowResize = true;
         }

        #region Sample Data

        #region Data
        string[] firstNames = new string[] 
                {
                    "Andrew",
                    "Nancy",
                    "Shelley",
                    "Regina",
                    "Yoshi",
                    "Antoni",
                    "Mayumi",
                    "Ian",
                    "Peter",
                    "Lars",
                    "Petra",
                    "Martin",
                    "Sven",
                    "Elio",
                    "Beate",
                    "Cheryl",
                    "Michael",
                    "Guylène"
                };

        string[] lastNames = new string[] 
                {
                    "Fuller",
                    "Davolio",
                    "Burke",
                    "Murphy",
                    "Nagase",
                    "Saavedra",
                    "Ohno",
                    "Devling",
                    "Wilson",
                    "Peterson",
                    "Winkler",
                    "Bein",
                    "Petersen",
                    "Rossi",
                    "Vileid",
                    "Saylor",
                    "Björn",
                    "Nodier"
                };

        static string[,] productNames = new string[,] 
                {
                    {"Black Tea", "1.95"},
                    {"Green Tea", "1.95"},
                    {"Caffè Espresso", "1.45"},
                    {"Doubleshot Espresso", "1.75"},
                    {"Caffè Latte", "2.25"},
                    {"White Chocolate Mocha", "2.35"},
                    {"Caramel Latte", "2.35"},
                    {"Caffè Americano", "1.65"},
                    {"Cappuccino", "2.10"},
                    {"Espresso Truffle", "2.45"},
                    {"Espresso con Panna", "1.81"},
                    {"Peppermint Mocha Twist", "1.99"}
                };

        public class EmployeeSaleRecord
        {
            public EmployeeSaleRecord(string Name, DateTime Date, int ProductId, int Quantity)
            {
                this._name = Name;
                this._date = Date;
                this._productid = ProductId;
                this._quantity = Quantity;
            }

            #region Private Members
            private string _name;
            private DateTime _date;
            private int _productid;
            private int _quantity;
            #endregion

            #region Properties

            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }

            public DateTime Date
            {
                get { return _date; }
                set { _date = value; }
            }

            public string Product
            {
                get { return productNames[_productid, 0]; }
            }

            public int Quantity
            {
                get { return _quantity; }
                set { _quantity = value; }
            }

            public double UnitPrice
            {
                get
                {
                    double unitPrice = double.Parse(productNames[_productid, 1], new System.Globalization.CultureInfo("en-US"));
                    return unitPrice;
                }
            }

            public double SalesAmount
            {
                get { return (double)_quantity * UnitPrice; }
            }


            #endregion
        }


        #endregion

        public List<EmployeeSaleRecord> listSaleRecord = new List<EmployeeSaleRecord>();

        private void PrepareGridData()
        {
            const int rowsToLoad = 1000;
            listSaleRecord.Clear();

            Random rand = new Random();

            for (int i = 0; i < rowsToLoad; i++)
            {
                int productId = rand.Next(0, productNames.Length / 2 - 1);
                int quantity = rand.Next(1, 5);
                listSaleRecord.Add(new EmployeeSaleRecord(
                    string.Format("{0} {1}",
                    firstNames[rand.Next(0, firstNames.Length - 1)],
                    lastNames[rand.Next(0, lastNames.Length - 1)]),
                    DateTime.Now.AddDays(-rand.Next(10, 100)),
                    productId,
                    quantity)
                    );
            }
        }

        #endregion

        public void SetTheme()
        {
            dataGrid.FontFamily = new FontFamily("Tahoma");
        }
  
        // Update values and reset binding 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DecimalValue = (int)Editor.Editor.Value;
            if (DecimalValue > 5)
            {
                DecimalValue = 5;
                this.Editor.Value = 5;
            }

            DateTimeFormatString = this.TextBoxDateTime.Text;

            if (this.CultureSettings.SelectedIndex >= 0)
            {
                CurrentCulture = this.info[this.CultureSettings.SelectedIndex];
            }
            this.dataGrid.DataBind();
            UpdateColumnsWidth(); 
        }

        public void UpdateColumnsWidth()
        {
            for (int i = 0; i < this.dataGrid.ColumnsHierarchy.Items.Count; i++)
            {
                if (i == 2 || i == 3)
                {
                    dataGrid.ColumnsHierarchy.Items[i].Width = 80;
                    continue;
                }
                else if (i == 0)
                {
                    dataGrid.ColumnsHierarchy.Items[i].Width = 160;
                    continue;
                }

                dataGrid.ColumnsHierarchy.Items[i].Width = 150;
            }
            dataGrid.Refresh();
        }

        // Update values and reset binding 
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            DecimalValue = 2;
            DateTimeFormatString = "d";
            CurrentCulture = null;
            this.dataGrid.DataBind();
            UpdateColumnsWidth();
        }

        public static CultureInfo CurrentCulture;
        public static int DecimalValue;
        public static string DateTimeFormatString;

        protected override void OnClosing(CancelEventArgs e)
        {
            this.listSaleRecord.Clear();
            this.listSaleRecord = null;
            base.OnClosing(e);
            ClearAll.Click -= new RoutedEventHandler(Button_Click_1);
            ApplyAll.Click -= new RoutedEventHandler(Button_Click);
          
            this.dataGrid.Dispose();
            this.dataGrid = null;
        }
    } // class CellEditing

    public class TextFormattingDemoCurrencyConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double dblVal = 0.0;
            if (value != null)
            {
                double.TryParse(value.ToString(), out dblVal);
            }
            else
            {
                return string.Empty;
            }

            return string.Format(TextFormatting.CurrentCulture, "{0:C" + TextFormatting.DecimalValue + "}", dblVal);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return double.Parse(value.ToString(), System.Globalization.NumberStyles.Currency);
        }
    }

    public class TextFormattingDemoDateTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string str = "d";
            try
            {
                str = string.Format(TextFormatting.CurrentCulture, "{0:" + TextFormatting.DateTimeFormatString + "}", (DateTime)value);
            }
            catch (Exception e)
            {
                str = string.Format(TextFormatting.CurrentCulture, "{0:d}", (DateTime)value);
                Console.WriteLine(e.Message);
            }

            return str;
        }

        public object ConvertBack(object value, Type targetType,
            object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                return DateTime.Parse(value.ToString());
            }
            else
            {
                return DateTime.Now.Date;
            }
        }
    }

    public class TextFormattingDemoTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string str = "d";
            try
            {
                str = string.Format(TextFormatting.CurrentCulture, "{0:" + TextFormatting.DateTimeFormatString + "}", (DateTime)value);
            }
            catch (Exception e)
            {
                str = string.Format(TextFormatting.CurrentCulture, "{0:d}", (DateTime)value);
                Console.WriteLine(e.Message);
            }

            return str;
        }

        public object ConvertBack(object value, Type targetType,
            object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                return DateTime.Parse(value.ToString());
            }
            else
            {
                return DateTime.Now.Date;
            }
        }
    }
}
